<template>
  <div class="p-6">
    <h2 class="text-2xl font-bold mb-6">数据看板</h2>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :span="6" v-for="card in cards" :key="card.label">
        <el-card :body-style="{ padding: '20px', color: '#fff', borderRadius: '12px', background: card.gradient }" shadow="hover">
          <div class="flex justify-between items-center">
            <div>
              <div class="text-lg">{{ card.label }}</div>
              <div class="text-3xl font-bold mt-2">{{ card.value }}</div>
            </div>
            <div class="text-4xl opacity-30">
              <i :class="card.icon"></i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <!-- 环形图：会员类型占比 -->
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="text-lg font-bold mb-2">会员类型占比</div>
          <div ref="pieRef" style="width:100%; height:300px"></div>
        </el-card>
      </el-col>

      <!-- 折线+柱状图：课程预约趋势 -->
      <el-col :span="16">
        <el-card shadow="hover">
          <div class="text-lg font-bold mb-2">课程预约趋势（近7天）</div>
          <div ref="barLineRef" style="width:100%; height:300px"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-card shadow="hover">
      <div class="text-lg font-bold mb-2">课程预约情况一览</div>
      <div id="main" ref="courseTrendRef" style="width:100%; height:300px"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import * as echarts from 'echarts'
import api from '@/util/api'

// 数据
const summary = ref({
  totalMembers: 0,
  totalCourses: 0,
  totalCoaches: 0,
  todayReservations: 0,
  vipMembers: 0,
  regularMembers: 0
})

// 卡片配置
const cards = computed(() => [
  { label: '会员总数', value: summary.value.totalMembers, gradient: 'linear-gradient(135deg, #6a11cb 0%, #2575fc 100%)', icon: 'el-icon-user' },
  { label: '课程总数', value: summary.value.totalCourses, gradient: 'linear-gradient(135deg, #ff9966 0%, #ff5e62 100%)', icon: 'el-icon-notebook-1' },
  { label: '教练总数', value: summary.value.totalCoaches, gradient: 'linear-gradient(135deg, #00c6ff 0%, #0072ff 100%)', icon: 'el-icon-s-custom' },
  { label: '今日预约', value: summary.value.todayReservations, gradient: 'linear-gradient(135deg, #f7971e 0%, #ffd200 100%)', icon: 'el-icon-date' }
])

// 图表引用
const pieRef = ref(null)
const barLineRef = ref(null)
const courseTrendRef = ref(null)
let pieChart = null
let barLineChart = null
let courseBar = null

// 获取汇总数据
const loadSummary = async () => {
  try {
    const res = await api.get('/charts/summary')
    summary.value = res
    renderPieChart()
  } catch (e) {
    console.error('获取汇总数据失败', e)
  }
}

// 获取趋势数据
const loadCourseTrend = async () => {
  try {
    const res = await api.get('/charts/courseTrend')
    //console.log(res)
    renderBarLineChart(res.dates, res.counts)
  } catch (e) {
    console.error('获取课程趋势失败', e)
  }
}

//获取课程列表
const loadCourses = async () => {
  try {
    const res = await api.get('/charts/all')
    console.log(res)
    renderCourseBar(res.names, res.counts)
  } catch (e) {
    console.error('获取课程列表失败', e)
  }
}

// 环形图：会员类型占比
const renderPieChart = () => {
  if (!pieRef.value) return
  pieChart = echarts.init(pieRef.value)
  const option = {
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    series: [
      {
        name: '会员类型',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: { show: true, position: 'outside', formatter: '{b}\n{d}%' },
        data: [
          { value: summary.value.vipMembers, name: 'VIP会员' },
          { value: summary.value.regularMembers, name: '普通会员' }
        ],
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ]
  }
  pieChart.setOption(option)
}

// 柱状+折线图：近7天预约趋势
const renderBarLineChart = (dates, counts) => {
  if (!barLineRef.value) return
  barLineChart = echarts.init(barLineRef.value)
  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: dates, axisLine: { lineStyle: { color: '#999' } } },
    yAxis: { type: 'value', axisLine: { lineStyle: { color: '#999' } }, splitLine: { lineStyle: { type: 'dashed' } } },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    series: [
      {
        name: '预约数',
        type: 'bar',
        data: counts,
        itemStyle: { color: '#409EFF' },
        barWidth: '40%'
      },
      {
        name: '预约趋势',
        type: 'line',
        data: counts,
        smooth: true,
        itemStyle: { color: '#67C23A' },
        lineStyle: { width: 3 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103, 195, 58, 0.4)' },
            { offset: 1, color: 'rgba(103, 195, 58, 0.1)' }
          ])
        }
      }
    ],
    animationDuration: 1000
  }
  barLineChart.setOption(option)
}

//课程预约数量柱状图
const renderCourseBar = (names, counts) => {
if (!courseTrendRef.value) return
  courseBar = echarts.init(courseTrendRef.value)
  const option = {
    xAxis: {
      type: 'category',
      data: names,
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: counts,
        type: 'bar'
      }
    ]
  };

  option && courseBar.setOption(option);
}





onMounted(() => {
  loadSummary()
  loadCourseTrend()
  loadCourses()
})
</script>

<style scoped>
.p-6 {
  padding: 24px;
}
.el-card {
  border-radius: 12px;
}
</style>
